#include "styleset.h"
#include "nddsetting.h"
#include "syntaxthememanager.h"
#include <QApplication>
#include <QGuiApplication>
#include <QPalette>
#include "ccnotepad.h"
#include <QFile>
#include <QDebug>
#include <QStyleHints>
#include <QProcess>
#include <QDir>
#include <Qsci/qscilexerglobal.h>
#if defined(Q_OS_WIN)
#include <QSettings>
#endif


QColor StyleSet::foldfgColor(0xe9, 0xe9, 0xe9, 100);
QColor StyleSet::foldbgColor(0xff, 0xff, 0xff);
QColor StyleSet::marginsBackgroundColor(0xf0f0f0);
QColor StyleSet::bookmarkBkColor(0xececec);

int StyleSet::m_curStyleId = 0;


GLOBAL_STYLE_OPS* StyleSet::s_global_style = nullptr;

StyleSet::StyleSet()
{
	init();
}

StyleSet::~StyleSet()
{}

void StyleSet::init()
{
	if (s_global_style == nullptr)
	{
		s_global_style = new GLOBAL_STYLE_OPS();

		s_global_style->default_style.styleId = 32;
		s_global_style->indent_guideline.styleId = 37;
		s_global_style->brace_highight.styleId = 34;
		s_global_style->bad_brace_color.styleId = 35;
		s_global_style->current_line_background_color.styleId = -1;
		s_global_style->select_text_color.styleId = -1;
		s_global_style->caret_colour.styleId = 2069;
		s_global_style->edge_colour.styleId = -1;
		s_global_style->line_number_margin.styleId = 33;
		s_global_style->bookmark_margin.styleId = -1;
		s_global_style->fold.styleId = -1;
		s_global_style->fold_active.styleId = -1;
		s_global_style->url_hoverred.styleId = -1;
	}
}

void StyleSet::setCommonStyle(QColor foldfgColor_, QColor foldbgColor_, QColor marginsBackgroundColor_, QString colorName)
{
	foldfgColor = foldfgColor_;
	foldbgColor = foldbgColor_;
	marginsBackgroundColor = marginsBackgroundColor_;

	QFile file(":/qss/lightbluestyle.qss");
	QString styleSheet;
	if (file.open(QIODevice::Text | QIODevice::ReadOnly))
	{
		styleSheet = file.readAll();
		QPalette palette;
		palette.setColor(QPalette::Window, foldbgColor_);
		palette.setColor(QPalette::Base, foldbgColor_);
		palette.setColor(QPalette::Button, foldbgColor_);
		qApp->setPalette(palette);

		if (colorName != "#EAF7FF")
		{
			styleSheet.replace("#EAF7FF", colorName);
		}
		qApp->setStyleSheet(styleSheet);
	}
	file.close();
}

void StyleSet::setSkin(int id)
{
	m_curStyleId = id;
	// 注意: 语法高亮主题现在由 SyntaxThemeManager 独立管理，不再受UI主题影响
	StyleSet::init();
	loadGolbalStyle();

	switch (id)
	{
	case DEFAULT_LIGHT:
		setDefaultLightStyle();
		// 自动切换到亮色语法主题
		SyntaxThemeManager::instance()->setSyntaxTheme(SYNTAX_LIGHT);
		break;
	case DEFAULT_DARK:
		setDefaultDarkStyle();
		// 自动切换到暗色语法主题
		SyntaxThemeManager::instance()->setSyntaxTheme(SYNTAX_DARK);
		break;
	case SYSTEM_THEME:
		setSystemThemeStyle();
		// 根据系统主题自动切换语法主题
		if (isSystemDarkMode())
		{
			SyntaxThemeManager::instance()->setSyntaxTheme(SYNTAX_DARK);
		}
		else
		{
			SyntaxThemeManager::instance()->setSyntaxTheme(SYNTAX_LIGHT);
		}
		break;
	case MAX_SE:
	default:
		// 默认使用亮色主题
		setDefaultLightStyle();
		SyntaxThemeManager::instance()->setSyntaxTheme(SYNTAX_LIGHT);
		break;
	}
}

void StyleSet::reloadGolbalStyleFromSetFile()
{
	loadGolbalStyle();
}

void StyleSet::loadGolbalStyle()
{
	QsciLexer* pLexer = ScintillaEditView::createLexer(L_GLOBAL);
	QsciLexerGlobal* pGlobalLexer = dynamic_cast<QsciLexerGlobal*>(pLexer);
	if (pGlobalLexer != nullptr)
	{
		One_Stype_Info* pAddr = &s_global_style->global_style;
		pGlobalLexer->setColor(pAddr->fgColor, pAddr->styleId);
		pGlobalLexer->setPaper(pAddr->bgColor, pAddr->styleId);
		pGlobalLexer->setFont(pAddr->font, pAddr->styleId);
	}
	delete pLexer;
}

bool StyleSet::isCurrentDeepStyle()
{
	switch (m_curStyleId)
	{
	case DEFAULT_LIGHT:
		return false;

	case DEFAULT_DARK:
		return true;

	case SYSTEM_THEME:
		// 系统主题：检查当前系统是否为暗色模式
		return isSystemDarkMode();

	default:
		// 默认为亮色主题
		return false;
	}
}

QString StyleSet::getStyleName(int styleId)
{
	static const QString style[MAX_SE] = {
		u8"亮色主题",
		u8"暗色主题",
		u8"跟随系统"
	};

	if (styleId >= 0 && styleId < MAX_SE)
		return style[styleId];
	else
		return style[DEFAULT_LIGHT];
}

void StyleSet::setCurrentStyle(int themes)
{
	setSkin(themes);
}

void StyleSet::setDefaultLightStyle()
{
	m_curStyleId = DEFAULT_LIGHT;
	qDebug() << "Setting default light theme (UI only)";
	
	// 设置UI控件的亮色调色板（只控制界面，不控制编辑器）
	QPalette palette;
	palette.setColor(QPalette::Window, QColor(240, 240, 240));
	palette.setColor(QPalette::WindowText, QColor(0, 0, 0));
	palette.setColor(QPalette::Base, QColor(255, 255, 255));
	palette.setColor(QPalette::AlternateBase, QColor(245, 245, 245));
	palette.setColor(QPalette::Text, QColor(0, 0, 0));
	palette.setColor(QPalette::Button, QColor(240, 240, 240));
	palette.setColor(QPalette::ButtonText, QColor(0, 0, 0));
	palette.setColor(QPalette::BrightText, QColor(255, 0, 0));
	palette.setColor(QPalette::Link, QColor(0, 0, 255));
	palette.setColor(QPalette::Highlight, QColor(0, 120, 215));
	palette.setColor(QPalette::HighlightedText, QColor(255, 255, 255));
	qApp->setPalette(palette);

	// 清空样式表，使用原生外观
	qApp->setStyleSheet("");
}

void StyleSet::setDefaultDarkStyle()
{
	m_curStyleId = DEFAULT_DARK;
	qDebug() << "Setting default dark theme (UI only)";
	
	// 设置UI控件的暗色调色板（只控制界面，不控制编辑器）
	QPalette palette;
	palette.setColor(QPalette::Window, QColor(53, 53, 53));
	palette.setColor(QPalette::WindowText, QColor(220, 220, 220));
	palette.setColor(QPalette::Base, QColor(42, 42, 42));
	palette.setColor(QPalette::AlternateBase, QColor(66, 66, 66));
	palette.setColor(QPalette::Text, QColor(220, 220, 220));
	palette.setColor(QPalette::Button, QColor(53, 53, 53));
	palette.setColor(QPalette::ButtonText, QColor(220, 220, 220));
	palette.setColor(QPalette::BrightText, QColor(255, 0, 0));
	palette.setColor(QPalette::Link, QColor(42, 130, 218));
	palette.setColor(QPalette::Highlight, QColor(42, 130, 218));
	palette.setColor(QPalette::HighlightedText, QColor(255, 255, 255));
	
	// 设置对话框和输入框的颜色
	palette.setColor(QPalette::ToolTipBase, QColor(53, 53, 53));
	palette.setColor(QPalette::ToolTipText, QColor(220, 220, 220));
	palette.setColor(QPalette::PlaceholderText, QColor(128, 128, 128));
	
	// 禁用状态的颜色
	palette.setColor(QPalette::Disabled, QPalette::WindowText, QColor(127, 127, 127));
	palette.setColor(QPalette::Disabled, QPalette::Text, QColor(127, 127, 127));
	palette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(127, 127, 127));
	
	qApp->setPalette(palette);

	// 标签页样式
	QString tabStyle = R"(
		QTabWidget::pane {
			border: 1px solid #3a3a3a;
			background: #2a2a2a;
		}
		QTabBar::tab {
			background: #3a3a3a;
			color: #dcdcdc;
			padding: 5px 10px;
			border: 1px solid #3a3a3a;
		}
		QTabBar::tab:selected {
			background: #2a2a2a;
			color: #ffffff;
			border-bottom: 2px solid #0078d4;
		}
		QTabBar::tab:hover {
			background: #4a4a4a;
		}
	)";
	qApp->setStyleSheet(tabStyle);
}

void StyleSet::setSystemThemeStyle()
{
	m_curStyleId = SYSTEM_THEME;
	qDebug() << "Setting system theme style";

	// 根据系统主题设置
	if (isSystemDarkMode())
	{
		qDebug() << "System is in dark mode, applying dark theme";
		setDefaultDarkStyle();
	}
	else
	{
		qDebug() << "System is in light mode, applying light theme";
		setDefaultLightStyle();
	}
	
	// 重新设置为系统主题ID（因为上面调用会改变ID）
	m_curStyleId = SYSTEM_THEME;
}

void StyleSet::setCommonStyle()
{
	// 兼容性保留，实际配色在各主题函数中设置
}

bool StyleSet::isSystemDarkMode()
{
#if defined(Q_OS_WIN)
	// Windows: 检查注册表
	QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", QSettings::NativeFormat);
	bool isDark = settings.value("AppsUseLightTheme", 1).toInt() == 0;
	qDebug() << "Windows theme detection - isDark:" << isDark;
	return isDark;
#elif defined(Q_OS_MACOS)
	// macOS: 使用 Qt6.5+ 的原生 API
	if (auto* styleHints = QGuiApplication::styleHints()) {
		bool isDark = styleHints->colorScheme() == Qt::ColorScheme::Dark;
		qDebug() << "macOS theme detection - isDark:" << isDark;
		return isDark;
	}
	return false;
#else
	// Linux: 检查 GTK 主题或 KDE 配置
	QByteArray desktop = qgetenv("XDG_CURRENT_DESKTOP").toLower();
	qDebug() << "Linux desktop environment:" << desktop;
	
	// 方法1: GNOME/Ubuntu - 使用 gsettings 命令
	if (desktop.contains("gnome") || desktop.contains("ubuntu")) {
		// 优先检查 color-scheme，这是更准确的主题检测方式
		QProcess colorScheme;
		colorScheme.start("gsettings", QStringList() << "get" << "org.gnome.desktop.interface" << "color-scheme");

		if (colorScheme.waitForFinished(1000)) {
			QString scheme = QString::fromLocal8Bit(colorScheme.readAllStandardOutput()).trimmed();
			// gsettings 返回的值带引号，如 'prefer-dark'，需要去除
			scheme = scheme.remove('\'').remove('"');
			qDebug() << "GNOME color scheme:" << scheme;
			if (scheme == "prefer-dark") {
				qDebug() << "Is dark mode: true (from color-scheme)";
				return true;
			} else if (scheme == "prefer-light") {
				qDebug() << "Is dark mode: false (from color-scheme)";
				return false;
			}
		}

		// 备用方法：检查 GTK 主题名称
		QProcess gsettings;
		gsettings.start("gsettings", QStringList() << "get" << "org.gnome.desktop.interface" << "gtk-theme");

		if (gsettings.waitForFinished(1000)) {
			QString theme = QString::fromLocal8Bit(gsettings.readAllStandardOutput()).trimmed();
			// gsettings 返回的值带引号，如 'Fluent-round-Dark-compact'，需要去除
			theme = theme.remove('\'').remove('"');
			qDebug() << "GNOME GTK theme:" << theme;
			bool isDark = theme.toLower().contains("dark");
			qDebug() << "Is dark mode:" << isDark;
			return isDark;
		}
	}
	
	// 方法2: KDE - 检查配置文件
	if (desktop.contains("kde") || desktop.contains("plasma")) {
		QString kdeglobalsPath = QDir::homePath() + "/.config/kdeglobals";
		if (QFile::exists(kdeglobalsPath)) {
			QSettings kdeSettings(kdeglobalsPath, QSettings::IniFormat);
			QString colorScheme = kdeSettings.value("General/ColorScheme", "").toString();
			qDebug() << "KDE color scheme:" << colorScheme;
			bool isDark = colorScheme.toLower().contains("dark");
			qDebug() << "Is dark mode:" << isDark;
			return isDark;
		}
	}
	
	// 方法3: 通用方法 - 检查 GTK3 配置文件
	QString gtk3ConfigPath = QDir::homePath() + "/.config/gtk-3.0/settings.ini";
	if (QFile::exists(gtk3ConfigPath)) {
		QSettings gtkSettings(gtk3ConfigPath, QSettings::IniFormat);
		QString themeName = gtkSettings.value("Settings/gtk-theme-name", "").toString();
		qDebug() << "GTK3 theme from config:" << themeName;
		bool isDark = themeName.toLower().contains("dark");
		qDebug() << "Is dark mode:" << isDark;
		return isDark;
	}
	
	qDebug() << "Unable to detect system theme, defaulting to light mode";
	return false;
#endif
}

void StyleSet::applyThemeByMode()
{
	if (m_curStyleId == SYSTEM_THEME)
	{
		setSystemThemeStyle();
	}
}

int StyleSet::getDefaultLightTheme()
{
	return DEFAULT_LIGHT;
}

int StyleSet::getDefaultDarkTheme()
{
	return DEFAULT_DARK;
}

QString StyleSet::getCurrentStyle()
{
	return getStyleName(m_curStyleId);
}

void StyleSet::setGlobalFgColor(int style, QColor color)
{
	// 实现全局前景色设置
}

void StyleSet::setGlobalBgColor(int style, QColor color)
{
	// 实现全局背景色设置
}

void StyleSet::setGlobalFont(int style, QFont font)
{
	// 实现全局字体设置
}